//
//  WQNetTool.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/7.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
import AFNetworking
///  请求方式枚举
///
///  - GET:  GET 请求
///  - POST: POST 请求
enum WQHttpRequestMethodType: String {
    case GET = "GET"
    case POST = "POST"
}

class WQNetTool: AFHTTPSessionManager {
    
    static let shareTool:WQNetTool = {
        let tool = WQNetTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
}


// MARK: - 首次加载新浪登陆服务器调用
extension WQNetTool {
    
    var appKey: String {return "1105377591"}
    var appSecret: String {return "350f22bde565206088ea68605f4210db"}
    var redirectUrl:String {return "http://www.baidu.com"}
    /// MARK: - OAuth认证加载新浪授权页面
    
    func loadData(urlString: String, parameters: AnyObject?, success: ((task:NSURLSessionDataTask, result: AnyObject?) -> ()), error:((task:NSURLSessionDataTask?,failure: NSError) -> ()))
    {
        
        GET(urlString, parameters: parameters, progress: nil, success: success, failure: error)
    }
}
// Cannot convert value of type '(task: NSURLSessionDataTask, result: AnyObject) -> ()' to expected argument type '((NSURLSessionDataTask, AnyObject?) -> Void)?'

// MARK: - OAuth认证网络参数
extension WQNetTool {
    
//    client_id     true	string	申请应用时分配的AppKey。
//    redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
//    https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code
    var oauthURLRequest: NSURLRequest {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"

        return NSURLRequest(URL: NSURL(string: urlStr)!)
    }
    
    /// MARK: - OAuth认证网络参数
    func loadAccessToken(code:String, finishedCallBack:((success: AnyObject?, failure: NSError?) -> ())) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let pramas = ["client_id": appKey,
                      "client_secret": appSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": redirectUrl]
        loadData(WQHttpRequestMethodType.POST, urlString: urlString, prama: pramas, result: finishedCallBack)
    }
}
// MARK: - 加载用户信息调用
extension WQNetTool {
    // MARK: - 加载用户信息调用
    func loadUserInfo(account: WQAccount, finishedCallBack:((success: AnyObject?, failure: NSError?) -> ())) {
        let pramas: [String: AnyObject]? = ["access_token": account.access_token!,
                        "uid": account.uid!]
        let urlStr = "https://api.weibo.com/2/users/show.json"
        loadData(WQHttpRequestMethodType.GET, urlString: urlStr, prama: pramas, result: finishedCallBack)
    }
    
    
}
// MARK: - 加载用户的微博数据
extension WQNetTool {
    
    // MARK: - 加载用户的微博数据 -> 下拉
    func loadStatus(account: WQAccount, since_id: Int, finishedCallBack:((success: AnyObject?, failure: NSError?) -> ())){
        var pramas: [String: AnyObject]? = ["access_token": account.access_token!]
        pramas!["since_id"] = since_id
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        loadData(WQHttpRequestMethodType.GET, urlString: urlStr, prama: pramas, result: finishedCallBack)
    }
    // MARK: - 加载用户的微博数据 -> 上拉
    func loadStatus(account: WQAccount, max_id: Int, finishedCallBack:((success: AnyObject?, failure: NSError?) -> ())){
        var pramas: [String: AnyObject]? = ["access_token": account.access_token!]
        pramas!["max_id"] = max_id - 1
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        loadData(WQHttpRequestMethodType.GET, urlString: urlStr, prama: pramas, result: finishedCallBack)
    }
}

// MARK: - 发送微博数据
extension WQNetTool {
    // MARK: - 发送微博数据 -> 文本
    func sendStatus(account: WQAccount, statusContent: String, finishedCallBack:((success: AnyObject?, failure: NSError?) -> ())){
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        let pramas: [String: AnyObject]? = ["access_token": account.access_token!,
                                            "status": statusContent]
        loadData(.POST, urlString: urlStr, prama: pramas, result: finishedCallBack)
    }
    	
}




// MARK: - 网络请求方法
extension WQNetTool {
    
    //测试百度接口
    var urlRequest: NSURLRequest {
        let urlString = "http://www.baidu.com"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        return request
    }
    /// MARK: - 网络请求方法
    func loadData(httpMethod:WQHttpRequestMethodType, urlString: String, prama: [String: AnyObject]?, result:((success: AnyObject?, failure: NSError?) -> ())) {
        
        let success = { (task:NSURLSessionDataTask, data: AnyObject?) -> () in
            //成功只传data
            result(success: data, failure: nil)
            }
        let error = { (task:NSURLSessionDataTask?, failure: NSError) -> () in
            //失败后只传failure
            result(success: nil, failure: failure)
        }
        
        switch httpMethod {
        case WQHttpRequestMethodType.GET:

             GET(urlString, parameters: prama, progress: nil, success: success, failure: error)
        case WQHttpRequestMethodType.POST:
             POST(urlString, parameters: prama, progress: nil, success: success, failure: error)
            
        }
    }
}





